package com.jianjun.project.system.profile;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Method;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.kit.JsonKit;
import com.jfinal.upload.UploadFile;
import com.jianjun.common.util.SecurityUtils;
import com.jianjun.framework.security.LoginUser;
import com.jianjun.framework.security.service.TokenService;
import com.jianjun.framework.web.domain.AjaxResult;
import com.jianjun.project.common.model.SysUser;
import com.jianjun.project.system.user.SysUserService;

import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.Objects;


/**
 * 个人信息 业务处理
 *
 * @author source
 */
@Path(value = "/system/user/profile")
public class SysProfileController extends Controller {
    @Inject
    SysUserService userService;
    @Inject
    TokenService tokenService;

    /**
     * 个人信息
     */
    public void index() {
        String method = getRequest().getMethod();
        //查询
        if (Method.GET.name().equals(method)) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            SysUser user = loginUser.getUser();
            AjaxResult ajax = AjaxResult.success(user);
            ajax.put("roleGroup", userService.selectUserRoleGroup(user.getUserId()));
            ajax.put("postGroup", userService.selectUserPostGroup(user.getUserId()));
            renderJson(ajax);
        }

        //修改
        if (Method.PUT.name().equals(method)) {
            SysUser user = JsonKit.parse(getRawData(), SysUser.class);
            LoginUser loginUser = SecurityUtils.getLoginUser();
            SysUser currentUser = loginUser.getUser();
            currentUser.setNickName(user.getNickName());
            currentUser.setEmail(user.getEmail());
            currentUser.setPhonenumber(user.getPhonenumber());
            currentUser.setSex(user.getSex());
            if (StrUtil.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(currentUser)) {
                renderJson(AjaxResult.error("修改用户'" + loginUser.getUser().getUserName() + "'失败，手机号码已存在"));
                return;
            }
            if (StrUtil.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(currentUser)) {
                renderJson(AjaxResult.error("修改用户'" + loginUser.getUser().getUserName() + "'失败，邮箱账号已存在"));
                return;
            }
            if (userService.updateUserProfile(currentUser)) {
                // 更新缓存用户信息
                tokenService.setLoginUser(loginUser);
                renderJson(AjaxResult.success());
                return;
            }
            renderJson(AjaxResult.error("修改个人信息异常，请联系管理员"));
        }


    }

    /**
     * 重置密码
     */
    public void updatePwd() {
        String oldPassword = get("oldPassword");
        String newPassword = get("newPassword");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userName = loginUser.getUser().getUserName();
        String password = loginUser.getUser().getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            renderJson(AjaxResult.error("修改密码失败，旧密码错误"));
            return;
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            renderJson(AjaxResult.error("新密码不能与旧密码相同"));
            return;
        }
        newPassword = SecurityUtils.encryptPassword(newPassword);
        if (userService.resetUserPwd(userName, newPassword) > 0) {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(newPassword);
            tokenService.setLoginUser(loginUser);
            renderJson(AjaxResult.success());
            return;
        }
        renderJson(AjaxResult.error("修改密码异常，请联系管理员"));

    }


    /**
     * 头像上传
     */
    public void avatar() {
        UploadFile file = getFile("avatarfile");
        if (Objects.nonNull(file)) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            String path = URLDecoder.decode(ResourceUtil.getResource("static").getPath(), StandardCharsets.UTF_8);
            if (path.startsWith("/") && path.contains(":")) {
                path = path.replaceFirst("/", "");
            }
            String avatar = Paths.get(path).toAbsolutePath().relativize(file.getFile().toPath()).toString();
            if (userService.updateUserAvatar(loginUser.getUser().getUserName(), avatar)) {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                renderJson(ajax);
                return;
            }
        }
        renderJson(AjaxResult.error("上传图片异常，请联系管理员"));
    }

}
